/* 
 +-----------------------------------------------
   ApiCloud 快速开发函数封装
 +-----------------------------------------------
   2016/12/1
 +-----------------------------------------------
 */
//封装app常用方法

(function(window){
    
	var App = {
		//服务端设置
		serverUrl : 'http://t.cn/E4AFedb',   //接口访问地址
		imgServerUrl:'http://t.cn/E4AFedb',	       //附件服务器地址
		debug:true,           //开启调试模式  true 显示调试日志console.log false不显示
		//ajax配置
		ajaxCache : true,     //ajax请求缓存
		//openWin 设置 
		allowEdit:true,       //打开新窗口 是否可以长按 复制 粘贴
		bounces:true,         //页面是否弹动
		slidBackEnabled:false,
		
		historyGestureEnabled:false,
		
		//_toast 延迟时长
		delay:2000,
		duration: 2000,       //持续时长，单位：毫秒
	    location: 'bottom',   //弹出位置，顶部、中间或底部
		//IOS配置项
		useWKWebView:false,    //IOS新页面渲染  为true时不能与其它未使用WKWebView加载的页面通用。
		
		photoBrowserFlag:false,
		
	}
	
	
	/**
	 * ajax请求
	 * @param string     url      ajax请求地址
	 * @param array      data     请求数据 json对象  {'1':1,'2':2}
	 * @param string    _method   请求类型 默认 post
	 * @param function  _call     请求成功回调函数
	 * @param string    _datatype 回调类型 默认 json
	 * @param filestr   _files    文件路径  {'file1':file}
	 */
	App.ajax = function(url,data,_method,_call,_datatype,_files){
		var _data = ( typeof arguments[1] == "undefined" || arguments[1] == null) ? {}  : arguments[1];
		var _method = ( typeof arguments[2] == "undefined" || arguments[2] == null) ? "post"  : arguments[2];
		var _datatype = ( typeof arguments[4] == "undefined" || arguments[4] == null) ? "json"  : arguments[4];
		var _files = ( typeof arguments[5] == "undefined" || arguments[5] == null) ? {}  : arguments[5];
		//判断是Apicloud还是H5
		var is_api = _isApiCloud();
		if(App.debug){
			var debugUrl="";
			$.each(_data,function(k,v){
				debugUrl += k+"="+v+"&";
			});
			console.log("请求地址："+url+"?"+debugUrl);
			if(_data)
				console.log("请求数据data："+ JSON.stringify(_data));
			if(_files)
				console.log("请求文件："+ JSON.stringify(_files));
		}
		if(is_api){
			api.ajax({
				url:url,
				method:_method,
				dataType:_datatype,
				cache:App.ajaxCache,
				data:{
					values:_data,
					files:_files
				}
			},function(ret,err){
				if(App.debug){
					var a = location.href;
	                var b = a.split("/");
	                var c = b.slice(b.length-1, b.length).toString(String);
	                console.log("返回内容："+ JSON.stringify(ret)+" \r\n请求页面："+c);
	                console.log("返回内容err："+ JSON.stringify(err));
				}
	
				if(ret){
					if ( typeof _call == "function") {
						_call(ret);
					}
				}else{
					if(err.msg !='网络请求超时，请稍后重试'){
						api.alert({msg:"网络连接失败，请稍后再试"});
					}
					api.refreshHeaderLoadDone();
					api.hideProgress();
					
				}
				
			});
		}else{
			$.ajax({
				url: url,
				data: _data,
				method:_method,
				dataType: "json",
				success: function(ret){
					console.log(ret);
					if ( typeof _call == "function") {
						_call(ret);
					}
				},
				error:function(){
					alert("网络连接失败，请稍后再试");
					return false;
				}
			});
		}
	}

	
	/** 打开新窗口 
	 * @param string name 窗口名称
	 * @param string url  地址
	 * @parem object pageParam  传递参数
	 */
	App.openWinByUrl = function(name, url,pageParam) {
			//判断是Apicloud还是H5
			var is_api = _isApiCloud();
			if(is_api){
				api.openWin({
					name : name,
					url : url + '.html',
					allowEdit:App.allowEdit ,
					useWKWebView:App.useWKWebView,
					slidBackEnabled:App.slidBackEnabled,
					pageParam :pageParam,
					delay:100
				});
			}else{
				var param ="";
				var _pageParam = ( typeof arguments[2] == "undefined" || arguments[2] == null) ? ""  : arguments[2];
				if(_pageParam  !=""){
					$.each(_pageParam,function(k,v){
						if(typeof v !='undefined'){
							param += k+"="+v+"&";
						}
					});
				}
				
				location.href= _ROOT+url+"?"+param;
			}
	};
	
	/** 打开新窗口 
	 * @param string name 窗口名称
	 * @param string url  地址
	 * @parem object pageParam  传递参数
	 */
	App.openFrame = function(name, url,_rect) {
		var _rect = ( typeof arguments[2] == "undefined" || arguments[2] == null) ? { x: 0,y: 0,w: 'auto',h: 'auto' }  : arguments[2];
		//判断是Apicloud还是H5
		var is_api = _isApiCloud();
		if(is_api){
			api.openFrame({
				name : name,
				url : url + '.html',
				allowEdit:App.allowEdit ,
				useWKWebView:true,
				historyGestureEnabled:App.historyGestureEnabled,
				bounces:App.bounces,
				slidBackEnabled:App.slidBackEnabled,
				pageParam :api.pageParam,
				rect:_rect
			});
		}
	};
	
	
	/**
	 * 图片浏览 
	 * array _data  数组
	 * int   _index  第几个开始
	 */
	App.photoBrowser = function(_data,_index){
		var _data = ( typeof arguments[0] == "undefined" || arguments[0] == null) ? []  : arguments[0];
		var _index = ( typeof arguments[1] == "undefined" || arguments[1] == null) ? 0  : arguments[1];
		var photoBrowser = api.require('photoBrowser');
		photoBrowser.open({
			images: _data,
			placeholderImg: 'widget://image/default.jpg',
			bgColor: '#000',
			activeIndex:_index
		}, function(ret, err) {
			if (ret) {
				App.photoBrowserFlag = true;
				if(ret.eventType=='click'){
					App.photoBrowserFlag = false;
					photoBrowser.close();
				}
			} else {
			   
			}
		});
	};
	
	App.photoBrowserClose = function(){
		App.photoBrowserFlag = false;
		photoBrowser.close();
	};
	
	
	
	//消息提示
	App.toast = function(msg,callback,delay){
		var delay = ( typeof arguments[2] == "undefined" || arguments[2] == null) ? App.delay  : arguments[2];  //延迟时长
		//判断是Apicloud还是H5
		var is_api = _isApiCloud();
		if(is_api){
			api.toast({
				duration:App.duration,
				location:App.location,
				msg:msg
			});
			if ( typeof callback == "function") {
				setTimeout(function(){
					callback();
				},delay); 
			}
		}else{
			alert(msg);
			if ( typeof callback == "function") {
				setTimeout(function(){
					callback();
				},delay); 
			}
		}
		
	};
	

	window.$app = App;
})(window);


$(function(){
	$("#back").click(function(){
		api.closeWin();
	})
});





window.loading_id = 0;
/**
 * 页面Loading
 */
function loading(frame) {
	
	var frame = (typeof arguments[0] == "undefined" || arguments[0] == null) ? "" : arguments[0];
	var UILoading = api.require('UILoading');
	UILoading.flower({
		center: {
			// x: 160,
			// y: 240
		},
		mask: '#fff',
		size: 30,
		fixed: true,
		fixedOn: frame
	}, function(ret) {
		window.loading_id = ret.id;
	});
}

/**
 * 页面Loading
 */

function closeloading() {
	//$("body").show();
	var uiloading = api.require('UILoading');
	uiloading.closeFlower({
		id: window.loading_id
	});
	
}



/**
 * 打开APP时验证当前是否有登陆信息，有登陆信息时则去服务端验证登陆信息是否过期或失效
 * @param token 
 */
var _isCheckToken = function(token){
	if( typeof arguments[0] == "undefined" || arguments[0] == null){
		var userinfo = $api.getStorage('userinfo');
		var _token = userinfo.token ;
	}else{
		var _token = arguments[0];
	}
	//判断是否需要验证
	if( typeof _token != "undefined" && _token != null  && _token != '' ){
		_ajax(App.serverUrl,{'token':_token},'post',function(ret){
			//判断是否失效时 清除登陆信息
			if(ret.code ==0){
				$api.rmStorage('userinfo');
			}
		})
	}
	
}



/**
 * 底部弹出框  一般用与上传头像
 * @param string title 标题
 * @param array  buttons 按钮
 * @param function _call 回调方法
 */
var _actionSheet = function(title, buttons,_call){
	api.actionSheet({
		title: title,
		cancelTitle: '取消',
		buttons:buttons,
		style:{
			fontPressColor:'#333',
			titleFontColor:'#333'
		}
	}, function(ret, err) {
		var index = ret.buttonIndex;
		if ( typeof _call == "function") {
			_call(ret,index);
		}
	});
	
}
	





/**
 * 判断是Apicloud还是H5
 * author lgp
 */
var  _isApiCloud = function(){
	if (typeof api !== 'undefined' && typeof api.openWin !== 'undefined' ) {
		return true;
	}
	else {
		return false;
	}
}


// 滚动到底部
function _scrollToEnd() {
	document.getElementsByTagName('body')[0].scrollTop = document.getElementsByTagName('body')[0].scrollHeight;
}



/**
 * 时间戳转时间
 * @param timespan 时间戳  非必填，为空时获取当前日期时间
 * @param is_time  是否获取时间，  为false时 值获取日期，为true时获取日期与时间
 */
function _formatDate(timespan,is_time) {
	if( typeof arguments[0] == "undefined" || arguments[0] == null){
		var now = new Date();
		var is_time = 1;
	}else{
		var now = new Date(timespan);
	}
	var year = now.getFullYear();
	var month = zeroize(now.getMonth() + 1);
	var date = zeroize(now.getDate());
	var hour = zeroize(now.getHours());
	var minute = zeroize(now.getMinutes());
	var second = zeroize(now.getSeconds());
	if(is_time){
		return year + "-" + month + "-" + date + "   " + hour + ":" + minute + ":" + second;
	}else{
		return year + "-" + month + "-" + date ;
	}
	
}

 var zeroize = function (value, length) {

    if (!length) length = 2;

    value = String(value);

    for (var i = 0, zeros = ''; i < (length - value.length); i++) {

        zeros += '0';

    }

    return zeros + value;

};

/**
 * 手机表情 用于把用utf16编码的字符转换成实体字符，以供后台存储
 * @param  {string} str 将要转换的字符串，其中含有utf16字符将被自动检出
 * @return {string}     转换后的字符串，utf16字符将被转换成&#xxxx;形式的实体字符
 */
function utf16toEntities(str) {
    var patt=/[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
    str = str.replace(patt, function(char){
            var H, L, code;
            if (char.length===2) {
                H = char.charCodeAt(0); // 取出高位
                L = char.charCodeAt(1); // 取出低位
                code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法
                return "&#" + code + ";";
            } else {
                return char;
            }
        });
    return str;
}

// 判断是否存在非法表情、字符
function checkEmoji(str) {
    var re =/[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则;//只能输入汉字和英文字母
    return !re.test(str)
    
}


// 判断是否是手机号
function _isPhone(str){
	var re =/^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
	return re.test(str);
}

// 判断密码
function _isPass(str){
	var re =/(^[a-zA-Z]+|[a-zA-Z]+[0-9]+|[0-9]+$)/;
	
	return re.test(str);
}
// 判断是否是正整数
function _isNumber(str) {
	var re = /^[0-9]*[1-9][0-9]*$/;
	return re.test(str);
}

// 是否是正浮点数
function _isDecimal(str) {
	var re = /^(([0-9]|([1-9][0-9]{0,9}))((\.[0-9]{1,2})?))$/;
	return re.test(str);
}



/**
 * 图片压缩 
 */
function imageFilter(path , _call , quality){
	var quality = ( typeof arguments[2] == "undefined" || arguments[2] == null  ||  arguments[2]=='') ? 0.3  : arguments[2];  //压缩比例
	var imageFilter = api.require('imageFilter');
	var savePath = api.cacheDir + "/" + _getNowFormatDate() + "/";  // 压缩文件的保存目录
	// 压缩文件生成的随机文件名称
	var savename = _newGuid() + ".jpg";
	imageFilter.compress({
	    img: path,
	    quality: quality,
	    save : {
			album : false,
			imgPath : savePath,
			imgName : savename
		}
	}, function(ret, err) {
	    if ( typeof _call == "function") {
			_call(ret,savePath + savename);
		}
	});
}

// 获取当前的时间，拼接成2015-11-09这样的格式，主要用于对图片进行时间分类
function _getNowFormatDate() {
	var date = new Date();
	var seperator1 = "-";
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var currentdate = year + seperator1 + month + seperator1 + strDate
	return currentdate;
}

// 生成guid,主要用于生成随机文件名
function _newGuid() {
	function S4() {
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
	}

	return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}


/**
* 将秒数换成时分秒格式
* 整理：www.jbxue.com
*/
  
function formatSeconds(value) {
    var theTime = parseInt(value);// 秒
    var theTime1 = 0;// 分
    var theTime2 = 0;// 小时
    if(theTime > 60) {
        theTime1 = parseInt(theTime/60);
        theTime = parseInt(theTime%60);
            if(theTime1 > 60) {
            theTime2 = parseInt(theTime1/60);
            theTime1 = parseInt(theTime1%60);
            }
    }
    	
    	if(theTime2 > 0) {
    		var result = videotime(parseInt(theTime2)) + ":" +   videotime(parseInt(theTime1)) + ":" + videotime(parseInt(theTime));
    	}else{
    		var result =  videotime(parseInt(theTime1)) + ":" + videotime(parseInt(theTime));
    	}
    	
        /*var result = ""+parseInt(theTime)+"秒";
        if(theTime1 > 0) {
        result = ""+parseInt(theTime1)+"分"+result;
        }
        if(theTime2 > 0) {
        result = ""+parseInt(theTime2)+"小时"+result;
        }*/
    return result;
}


 var videotime = function (value, length) {

    if (!length) length = 2;

    value = String(value);

    for (var i = 0, zeros = ''; i < (length - value.length); i++) {

        zeros += '0';

    }

    return zeros + value;

};


// PHP时间戳转时间
function _trans_php_time_to_str(timestamp, n) {
	update = new Date(timestamp);
	//时间戳要乘1000
	year = update.getFullYear();
	month = (update.getMonth() + 1 < 10) ? ('0' + (update.getMonth() + 1)) : (update.getMonth() + 1);
	day = (update.getDate() < 10) ? ('0' + update.getDate()) : (update.getDate());
	hour = (update.getHours() < 10) ? ('0' + update.getHours()) : (update.getHours());
	minute = (update.getMinutes() < 10) ? ('0' + update.getMinutes()) : (update.getMinutes());
	second = (update.getSeconds() < 10) ? ('0' + update.getSeconds()) : (update.getSeconds());
	if (n == 1) {
		return (year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
	} else if (n == 2) {
		return (year + '-' + month + '-' + day);
	} else {
		return (year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
	}
}


function _empty(el){
	var strVar = "";
    strVar += " <div class=\"preview\" style=\"height:200px;\">\n";
    strVar += "        <h1 class=\"H-text-align-center H-font-size-28 H-theme-font-color9 H-font-family-Arial H-margin-vertical-top-10 H-margin-vertical-bottom-10\" >HI,I'M Hui.<\/h1>\n";
    strVar += "     \n";
    strVar += "    <\/div>\n";
    
    return (strVar);
}



function _share(share_name , share_thumb , fnssfdurl){

	var share_name= ( typeof arguments[0] == "undefined" || arguments[0] == null) ? '武搏汇'  : arguments[0];
	var share_thumb= ( typeof arguments[1] == "undefined" || arguments[1] == null) ? 'timeline'  : arguments[1];
	var fnssfdurl= ( typeof arguments[2] == "undefined" || arguments[2] == null) ? App.shareUrl  : arguments[2];
	
	
	var dialogBox = api.require('dialogBox');
	dialogBox.actionMenu ({
	    rect:{
	        h: 150
	    },
	    texts:{
	         cancel: '取消'
	    },
	    items:[
	    {
	        text: '微信',
	        icon: 'widget://image/icons-weixinzhifu.png'
	    },
	    {
	        text: '朋友圈',
	        icon: 'widget://image/icon-pengyouquan.png'
	    }
	    ],
	    styles:{
	        bg:'#FFF',
	        column: 2,
	        itemText: {
	            color: '#000',
	            size: 12,
	            marginT:8
	        },
	        itemIcon:{
	            size:50
	        },
	        cancel:{  
	            bg: 'fs://icon.png',   
	            color:'#000',          
	            h: 44 ,                 
	            size: 14       
	        }
	    }
	}, function(ret){
		if(ret.eventType =='cancel'){
			dialogBox.close({
			    dialogName: 'actionMenu'
			});
		}
		var index =ret.index;
		if(ret.eventType == 'click'){
			//检测微信是否安装
			var wx = api.require('wx');
			wx.isInstalled(function(ret, err) {
			    if (ret.installed) {
			    	if(index ==0){
						 shareWx(share_name,share_thumb,fnssfdurl,'session');
					}
					if(index ==1){
						 shareWx(share_name,share_thumb,fnssfdurl,'timeline');
					}
			       
			    } else {
			        _toast('请先安装微信客户端');
			    }
			});

			
		}
	    //alert(JSON.stringify(ret));
	});
}


/**、
 * 微信分享 
 */
function shareWx(title,thumb,url,scene){

	var title= ( typeof arguments[0] == "undefined" || arguments[0] == null) ? '武搏汇'  : arguments[0];
	var scene= ( typeof arguments[3] == "undefined" || arguments[3] == null) ? 'timeline'  : arguments[3];
	var wx = api.require('wx');
	wx.shareWebpage({
	    apiKey: 'wx2cc23119d96709e5',
	    scene: scene,
	    title: title,
	    description: title,
	    thumb: '../images/logo.png',
	    contentUrl: url
	}, function(ret, err) {
	    if (ret.status) {
	        _toast('分享成功');
	    } else {
	    	if(ret.status==-1){
	    		_toast("未知错误");
	    	}else if(ret.status==2){
	    		_toast("取消分享");
	    	}else if(ret.status==3){
	    		_toast("分享失败");
	    	}else{
	    		_toast("分享失败");
	    	}
	        
	    }
	});

}



function _loginout(){
	//非法操作退出登录
	$api.rmStorage('userinfo');
	localStorage.removeItem('uid');
	localStorage.removeItem('token');
	localStorage.removeItem('portrait');
	localStorage.removeItem('username');
	//广播用户登陆刷新用户信息
		api.sendEvent({
            name:'event_userinfo',
            extra:{
            	'userinfo':ret.data
            }
        });
	_toast('非法操作',function(){
		api.closeToWin({
			name:'root'
		});
	})
}

//列表加载没有更多内容
function moreEmpty(){
	var emptyStr = '<div class="H-flexbox-horizontal"><span class="H-timeline H-flex-item H-font-size-12 H-theme-font-color-333 H-text-align-center H-padding-vertical-both-8">没有内容了</span></div>';
	$("body").append(emptyStr);
}



$(function(){


	$("#back_btn").click(function(){
		var closeName = api.pageParam.closeName;
		if( closeName ){
			api.closeToWin({
	            name: closeName
	        });
		}else{
			api.closeWin();
		}
	});
	
	$(".list-activety-more ").click(function(){
		var flag = $(this).attr('data-flag');
		if( flag == 1){
			$(this).parent('div').css('height','50px');
			$(this).attr('data-flag' , 0);
			
			$(this).find('i').addClass('icon-xiangxia2');
		} else {
			$(this).parent('div').css('height','auto');
			$(this).attr('data-flag' , 1);
			$(this).find('i').removeClass('icon-xiangxia2');
			$(this).find('i').addClass('icon-xiangshang2');
		}
		
		event.stopPropagation();
		
	})

})


